<?php


namespace app\service;

use app\model\AdminMenu;
use app\model\Plugin;
use app\model\Plugin as PluginModel;
use think\facade\App;

class PluginService
{
    public static function install($pluginName)
    {
        $class = get_plugin_class($pluginName);
        if (!class_exists($class)) {
            return lang('插件不存在');
        }

        $pluginModel = new Plugin();
        $pluginCount = $pluginModel->where('name', $pluginName)->count();

        if ($pluginCount > 0) {
            return lang('插件已安装');
        }

        $plugin = new $class;
        $info   = $plugin->info;
        if (!$info || !$plugin->checkInfo()) {//检测信息的正确性
            return lang('插件信息缺失');
        }

        $installSuccess = $plugin->install();
        if (!$installSuccess) {
            return lang('插件预安装失败');
        }

        if (!empty($plugin->hasAdmin)) {
            $info['has_admin'] = 1;
        } else {
            $info['has_admin'] = 0;
        }

        $info['config'] = json_encode($plugin->getConfig());

        $pluginModel->save($info);

        return true;
    }

    public static function uninstall($pluginName)
    {
        $class      = get_plugin_class($pluginName);
        $pluginName = parse_name($pluginName);

        Plugin::where('name', $pluginName)->delete();

        if (class_exists($class)) {
            $plugin = new $class;

            $uninstallSuccess = $plugin->uninstall();
            if ($uninstallSuccess !== true) {
                return lang("插件卸载失败") . $uninstallSuccess;
            }
        }

        // 删除后台菜单

        // 删除权限规则

        // 删除路由
        $routeDir = App::getRootPath() . "route" . DIRECTORY_SEPARATOR;
        $files = glob($routeDir . '*.php');

        foreach ($files as $file) {
            $fileName = pathinfo($file, PATHINFO_FILENAME);
            if (strpos($fileName, 'plugin_' . $pluginName) !== false) {
                unlink($file);
            }
        }

        return true;
    }

    public static function editStatus($pluginName, $status)
    {
        $pluginName = parse_name($pluginName);

        $remark = 'plugin_' . $pluginName;

        $adminMenuModel = new AdminMenu();
        if ($status == 2) {
            // 删除路由
            $routeDir = App::getRootPath() . "route" . DIRECTORY_SEPARATOR;
            $files = glob($routeDir . '*.php');

            foreach ($files as $file) {
                $fileName = pathinfo($file, PATHINFO_FILENAME);
                if (strpos($fileName, 'plugin_' . $pluginName) !== false) {
                    unlink($file);
                }
            }

            // 禁用菜单
            $adminMenuModel->where('remark', $remark)->update(['status' => 2]);
        } else {
            // 启用
            $adminMenuModel->where('remark', $remark)->update(['status' => 1]);
        }

        $pluginModel = new PluginModel();

        return $pluginModel->edit(['name' => $pluginName], ['status' => $status]);
    }

}
